#include <assert.h>
#include "ourhdr.h"
#include "fat32.h"

static struct alloc_file_content* phead;

void cyclic_write_fat32(const struct filsys_fat32* dosfs, int fd, const void *buf, size_t size){
	if(!phead){
		phead = (struct alloc_file_content*)malloc(sizeof(struct alloc_file_content));
		lseek(fd, clus2off(dosfs, get_alloc_file_clus(dosfs)), SEEK_SET);
		read(fd, phead, sizeof(struct alloc_file_content));
	}
	size_t left = size;		/* left bytes to write */
	void *ptr = buf;

	int n;
	while(left){
		lseek(fd, pos2off(dosfs, phead->writePos), SEEK_SET);
		if(left < VIDEO_SZ - phead->writePos.offset){
			n = write(fd, ptr, left);
			phead->writePos.offset += n;
		}else {
			n = write(fd, ptr, VIDEO_SZ - phead->writePos.offset);
			phead->writePos.offset = 0;
			if(phead->writePos.file == phead->lastFolderFileNum -1 && phead->writePos.folder == phead->folderNum -1){
				phead->writePos.file = 0;
				phead->writePos.folder = 0;
			} else if(phead->writePos.file == VIDEOS_PER_PACK - 1){
				phead->writePos.file = 0;
				phead->writePos.folder ++;
			} else{
				phead->writePos.file ++;
			}
		}
		left -= n;
		ptr = (char*)ptr + n;
	}
	assert(left == 0);
	lseek(fd, clus2off(dosfs, get_alloc_file_clus(dosfs)), SEEK_SET);
	write(fd, phead, sizeof(struct alloc_file_content));
	

#if 0
	/* read allocfile to get the write writePos. */
	lseek(fd, clus2off(data_start,ALLOC_FILE_CLUS(folderNum)), SEEK_SET);
	read(fd, &header, sizeof(header) );

	disp(header.writewritePos.folder);
	disp(header.writewritePos.file);
	disp(header.writewritePos.offset);

	uint64_t sum = ((header.folderNum - 1) * VIDEOS_PER_PACK + header.lastFolderFileNum ) * VIDEO_SZ;
	uint64_t cur = (header.writewritePos.folder * VIDEOS_PER_PACK + header.writewritePos.file) * VIDEO_SZ + header.writewritePos.offset;
	disp(cur);
	disp(sum);
	if(cur + size > sum){
		lseek(fd, clus2off(data_start, VIDEO_FILE_CLUS(folderNum, 0, 0)) + cur, SEEK_SET);
		write(fd, buf, sum - cur);
		lseek(fd, clus2off(data_start, VIDEO_FILE_CLUS(folderNum, 0, 0)), SEEK_SET);
		write(fd, buf + sum - cur, cur + size - sum);
	} else {
		lseek(fd, clus2off(data_start, VIDEO_FILE_CLUS(folderNum, 0, 0)) + cur, SEEK_SET);
		write(fd, buf, size);
	}
	cur = (cur + size) % sum;
	header.writewritePos.offset = cur % VIDEO_SZ;
	cur = cur / VIDEO_SZ;
	header.writewritePos.file = cur % VIDEOS_PER_PACK;
	cur = cur / VIDEOS_PER_PACK;
	header.writewritePos.folder = cur;

	lseek(fd, clus2off(data_start,ALLOC_FILE_CLUS(folderNum)), SEEK_SET);
	write(fd, &header, sizeof(header));
#endif


}
